<template>
  <div class="wrapper">
    <div class="box">
      {{ entryId }}
      <div class="container">
        <div class="item" data-id="1">Box 1</div>
        <div class="item" data-id="2">Box 2</div>
        <div class="item" data-id="3">Box 3</div>
        <div class="item" data-id="4">Box 4</div>
        <div class="item" data-id="5">Box 5</div>
        <div class="item" data-id="6">Box 6</div>
      </div>
    </div>
    <div class="action">
      <div class="btn" @click="test">测试</div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
console.log('当前系统时间：', dayjs().format('YYYY-MM-DD HH:mm:ss'))
export default {
  components: {},
  props: {},
  data() {
    return {
      entryId: undefined,
      loading: false
    }
  },
  computed: {},
  watch: {
    entryId(nweVal, oldVal) {
      this.getData()
    }
  },
  created() {},
  mounted() {
    // 1. 创建 IntersectionObserver 实例
    const observer = new IntersectionObserver(
      (entries, observer) => {
        entries.forEach(entry => {
          // 2. 如果目标元素进入视口
          if (entry.isIntersecting) {
            const target = entry.target
            let id = target.dataset.id
            this.entryId = id
            entry.target.style.backgroundColor = 'red' // 改变背景颜色
            // observer.unobserve(entry.target) // 停止观察该元素
          } else {
            const target = entry.target
            target.style.backgroundColor = 'blue' // 改变背景颜色
          }
        })
      },
      {
        root: null, // 默认为视口
        rootMargin: '0px', // 扩展或缩小根元素的边界
        threshold: 0.5 // 当 50% 的目标元素进入视口时触发回调
      }
    )

    // 3. 观察所有带有 .box 类的元素
    document.querySelectorAll('.item').forEach(box => {
      observer.observe(box)
    })
  },
  activated() {},
  deactivated() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  methods: {
    getData() {
      this.loading = true
    },
    test() {}
  },
  filters: {}
}
</script>
<style scoped lang="scss">
@mixin oneline {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.wrapper {
  height: 100%;
  position: relative;
  border: 1px solid #000;
  .box {
    padding: 15px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2), 0 0 6px rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 800px;
    height: 600px;
    .container {
      // height: 1500px; /* 使页面可滚动 */
      border: 1px solid red;
      height: 200px;
      height: 500px;
      overflow: auto;
      position: absolute;
      top: 0;
      left: 50%;
      transform: translate(-50%, 50px);

      .item {
        width: 200px;
        height: 200px;
        margin: 20px 20px;
        background-color: lightgray;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        transition: background-color 0.5s ease;
      }
    }
  }
}
</style>
